using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PowerManage.Entity;
using PowerManage.Entity.Enums;

namespace PowerManage.API.AuditLog;

/// <summary>
/// 审核日志帮助类
/// </summary>
public class AuditLogHelper
{
    /// <summary>
    /// 获取请求日志参数
    /// ActionContext 替换 HttpContext ：ActionContext包含了更多与mvc控制器操作的信息
    /// </summary>
    /// <param name="action">根据上下文取到request对象，获取接口url，方法，参数，浏览器信息等</param>
    /// <param name="userManager">根据identity获取登录用户信息</param>
    /// <returns></returns>
    public static EleAuditLog GetRequestAuditLog(ActionContext action, UserManager<EleUser> userManager)
    {
        //审核日志
        var eleAuditLog = new EleAuditLog();
        eleAuditLog.ApiUrl = action.HttpContext.Request.Path;
        eleAuditLog.Method = action.HttpContext.Request.Method;

        eleAuditLog.AuditLogType = AuditLogType.Info;
        var name = action.HttpContext.User.Identity.Name;
        if (!string.IsNullOrEmpty(name))
        {
            var eleUser = userManager.FindByNameAsync(name).Result;
            if (eleUser != null)
                eleAuditLog.CreatorId = eleUser.Id;
        }

        var ipAddress = action.HttpContext.Connection.RemoteIpAddress;
        eleAuditLog.ClientIpAddress = ipAddress == null ? String.Empty : ipAddress.MapToIPv4().ToString();
        eleAuditLog.BrowserInfo = action.HttpContext.Request.Headers.ContainsKey("User-Agent")
            ? action.HttpContext.Request.Headers["User-Agent"]
            : string.Empty;

        // 处理请求参数并应用脱敏
        eleAuditLog.Parameters = GetDesensitizedParameters(action);

        return eleAuditLog;
    }

    /// <summary>
    /// 获取脱敏处理后的请求参数
    /// </summary>
    /// <param name="action">操作上下文</param>
    /// <returns></returns>
    private static string GetDesensitizedParameters(ActionContext action)
    {
        var parameters = string.Empty;

        if (action.HttpContext.Request.Method == "GET")
        {
            // GET请求：处理查询参数
            var json = new JObject();
            foreach (var item in action.HttpContext.Request.Query)
            {
                json.Add(item.Key, item.Value.ToString());
            }

            parameters = JsonConvert.SerializeObject(json);
        }
        else
        {
            // POST/PUT等请求：读取请求体
            using (StreamReader reader = new StreamReader(action.HttpContext.Request.Body))
            {
                action.HttpContext.Request.Body.Position = 0;
                parameters = reader.ReadToEndAsync().Result;
                //重置流的位置，以便在后续的处理中可以再次读取数据
                action.HttpContext.Request.Body.Position = 0;
            }
        }

        // 如果没有参数，直接返回空字符串
        if (string.IsNullOrEmpty(parameters))
        {
            return string.Empty;
        }

        // 应用脱敏处理
        return ApplyDesensitization(action, parameters);
    }

    /// <summary>
    /// 应用脱敏处理
    /// </summary>
    /// <param name="action">操作上下文</param>
    /// <param name="parameters">原始参数</param>
    /// <returns></returns>
    private static string ApplyDesensitization(ActionContext action, string parameters)
    {
        try
        {
            var json = new JObject();
            foreach (var item in action.ActionDescriptor.Parameters)
            {
                var value = GetParameterValue(item, action, parameters);
                json.Add(item.Name, value);
            }

            return JsonConvert.SerializeObject(json);
        }
        catch
        {
            // 如果脱敏处理失败，返回原始参数（避免日志记录失败）
            return parameters;
        }
    }

    /// <summary>
    /// 获取参数值
    /// </summary>
    /// <param name="parameterDescriptor">参数描述符</param>
    /// <param name="action">操作上下文</param>
    /// <param name="parameters">参数json字符串</param>
    /// <returns></returns>
    private static string GetParameterValue(ParameterDescriptor parameterDescriptor, ActionContext action,
        string parameters)
    {
        //如果参数是从URL路径中绑定的（如路由参数），则从路由数据中获取参数值
        var bindingSource = parameterDescriptor.BindingInfo?.BindingSource;
        if (bindingSource == BindingSource.Path)
        {
            //根据路由获取参数的值
            return action.RouteData.Values.GetValueOrDefault(parameterDescriptor.Name)?.ToString() ?? string.Empty;
        }
        else
        {
            try
            {
                //根据参数类型反序列化，获取参数值
                var parameterObject = JsonConvert.DeserializeObject(parameters, parameterDescriptor.ParameterType);
                //重新序列化，获取脱敏处理的字符串
                return JsonConvert.SerializeObject(parameterObject);
            }
            catch
            {
                // 如果反序列化失败，返回原始参数
                return parameters;
            }
        }
    }
}